"""

中国农业银行账户管理系统

1.编程实现：仔细业务之间的包含关系，并完成以下编程需求，要适当提高代码的可复用性。
    a)用户：账号（str：系统随机产生8位数字）、    random.randint(8)
    账户类型（int）、姓名(str)、密码(int:6位数字)、地址、存款余额(int)、开户行（银行的名称（str））
    b)地址：国家(str)、省份(str)、街道(str)、门牌号(str)
    c)银行：能存储100用户的库(字典)、
    本银行名称（比如：中国农业银行的昌平沙河支行,str）

"""
import random
def init_bank(bank_name):   # 初始化存储100用户的银行
    return {
        "name":bank_name,
        "users":{}   # 用户信息
    }


def user_account(bank):  # 系统随机生成8位数字
    while True:
        account_id = str(random.randint(10000000,99999999))
        if account_id not in bank["users"]:
            return account_id

def open_account(bank,account_type,name,passwd,address,balance): # 开户功能
    if len(bank["users"]) >= 100:
        return 3 # "银行用户库已满，不可再开具新用户。"
    account_id = user_account(bank)   # 调用user_account函数生成新的账号
    # 生成用户信息（字典的形式）
    user_info = {
        "account_id":account_id,
        "account_type":account_type,
        "name":name,
        "passwd":passwd,
        "address":address,
        "balance":balance,
        "bank_name":bank["name"]

    }
    bank["users"][account_id] = user_info
    return 1 # "开户操作成功。"

def save_money(bank,account_id,amount):   # 存钱功能
    if account_id not in bank["users"]:
        return False
    if amount <= 0:
        return False
    bank["users"][account_id]["banlance"] += amount
    return "存钱操作成功"

def get_money(bank,account_id,passwd,amount):  # 取钱功能
    if account_id not in bank["users"]:
        return 1 # "账户不存在"
    user = bank["users"][account_id]
    if user["passwd"] != passwd:
        return 2 # "密码不对"
    if amount <= 0 or user["balance"] < amount:
        return 3 # "钱不够"
    user["balance"] -= amount
    return "取钱操作成功"

def trans_money(bank,out_id,come_id,passwd,amount):   # 转账功能
    if out_id not in bank["users"] or come_id not in bank["users"]:
        return 1 # "账号不存在"
    out_user = bank["users"][out_id]
    if out_user["passwd"] != passwd:
        return 2 # "密码不对"
    if amount <= 0 or out_user["balance"] < amount:
        return 3 # "钱不够"
    out_user["balance"] -= amount
    bank["users"][come_id]["balance"] += amount
    return "转账操作成功"

def query(bank,account_id,passwd):  #  查询账户功能
    if account_id not in bank["users"]:
        print("该用户不存在")
        return
    user = bank["users"][account_id]
    if user["passwd"] != passwd:
        print("密码不正确")
        return
    address = user["address"]
    print(f"当前账号:{user['account_id']}")
    print(f"密码:{user['passwd']}")
    print(f"余额:{user['balance']}元")
    print(f"用户居住地址:{address['country']}{address['province']}{address['street']}{address['door_number']}")
    print(f"当前账户的开户行:{user['bank_name']}")

def atm_interface(bank):  # 银行功能主界面
    while True:
         print("\n=============================")
         print("       中国农业银行账户管理系统")
         print("=============================")
         print("               1.开户")
         print("               2.存钱")
         print("               3.取钱")
         print("               4.转账")
         print("               5.查询")
         print("               6.bye")
         print("===========================")
         choice = input("请选择要执行的功能操作(1-6):".split())

         if choice == "1":
             try:
                 account_type = int(input("请输入用户类型（整数）:"))
                 name = input("请输入姓名:").strip()
                 passwd = int(input("请输入6位数字密码:"))
                 if len(str(passwd)) != 6:
                     print("格式错误，密码必须6位数字")
                     continue
                 address = {
                     "country":input("请输入国家").strip(),
                     "province":input("请输入省份:").strip(),
                     "street":input("请输入街道:").strip(),
                     "door_number":input("请输入门牌号:").strip()

                 }
                 balance = int(input("请输入初始存款金额:"))
                 if balance < 0:
                     print("金额不能为负数")
                     continue
                 result = open_account(bank,account_type,name,passwd,address,balance)
                 if result == 1:
                     print("开户成功！您的账号为:",[k for k,v in bank["users"].items() if v["name"] == name][0])
                 elif result == 3:
                     print("开户失败，用户库存已满，最多100人")
             except ValueError:
                 print("输入错误，请检查数字格式")
         elif choice == "2":
             try:
                 account_id = input("请输入账号:").strip()
                 amount = int(input("请输入存款金额:"))
                 if amount <= 0:
                     print("错误，存款金额必须为正数！")
                     continue
                     success = save_money(bank,account_id,amount)
                     print("存钱成功" if success else "存钱失败，账号不存在")
             except ValueError:
                 print("输入错误，金额必须是整数")

         elif choice == "3":
             try:
                 account_id = input("请输入账号").strip()
                 passwd = int(input("请输入密码:"))
                 amount = int(input("请输入取款金额"))
                 result = get_money(bank,account_id,passwd,amount)
                 if result == 0:
                     print("取钱成功")
                 elif result == 1:
                     print("取钱失败，账号不存在")
                 elif result == 2:
                     print("取钱失败，密码不对")
                 elif result == 3:
                     print("取钱失败，钱不够")
             except ValueError:
                 print("输入错误。格式不正确")
         elif choice == "4":
             try:
                 out_id = input("请输入要转出的账号:").strip()
                 come_id = input("请输入转入的账号:").strip()
                 passwd = int(input("请输入转出账号的密码:"))
                 amount = int(input("请输入转账金额:"))
                 result = trans_money(bank,out_id,come_id,passwd,amount)
                 if result == 0:
                     print("转账成功")
                 elif result == 1:
                     print("转账失败，账号不对")
                 elif result == 2:
                     print("转账失败，密码不对")
                 elif result == 3:
                     print("转账失败，钱不够")
             except ValueError:
                 print("输入错误，格式不正确")

         elif choice == "5":
             try:
                 account_id = input("请输入账号:").strip()
                 passwd = int(input("请输入密码:"))
                 query(bank,account_id,passwd)
             except ValueError:
                 print("输入错误，密码必须是数字")

         elif choice == "6":
             print("感谢使用，bye~")
             break
         else:
             print("无效选项，请重新选择")


if __name__ == "__main__":
    bank = init_bank("中国农业银行昌平沙河支行")
    atm_interface(bank)










